package com.xb.cloud.common;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonUtils {

	/**
	 * 将json string转化成Java Bean
	 * 
	 * @param jsonString
	 * @param beanCalss
	 * @return
	 */
	public static <T> T jsonToBean(String jsonString, Class<T> beanCalss) {
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		T bean = JSONObject.toJavaObject(jsonObject, beanCalss);
		return bean;
	}

	/**
	 * 将bean转化成json String
	 * 
	 * @param bean
	 * @return
	 */
	public static String beanToJson(Object bean) {
		return JSON.toJSONString(bean);
	}

	/**
	 * 目标JSON字符串转化成对象
	 * 
	 * @param json
	 * @param cls
	 * @return
	 */
	public static <T> T toObject(String json, Class<T> cls) {
		return JSON.parseObject(json, cls);
	}

	/**
	 * 目标JSOn串转化成List
	 * 
	 * @param json
	 * @param cls
	 * @return
	 */
	public static <T> List<T> toObjectArray(String json, Class<T> cls) {
		return JSON.parseArray(json, cls);
	}

	/**
	 * 将对象转换json对象
	 * 
	 * @Title parseObject
	 * @param json
	 * @return
	 */
	public static JSONObject parseObject(Object bean) {
		return JSON.parseObject(beanToJson(bean));
	}

	/**
	 * 转换json对象
	 * 
	 * @Title parseObject
	 * @param json
	 * @return
	 */
	public static JSONObject parseObject(String json) {
		return JSON.parseObject(json);
	}

	/**
	 * 将json数组字符串转换成json数组
	 * 
	 * @Title toJsonArray
	 * @param json
	 * @return
	 */
	public static JSONArray parseArray(String json) {
		return JSON.parseArray(json);
	}
	/**
	 * 转换包含long类型的属性字段，因为long型在前台 js会丢失进度
	 * @Title beanToStringWithLong
	 * @param object
	 * @return
	 */
	public static String beanToStringWithLong(Object object) {
		final SerializeConfig resultJsonConfig = new SerializeConfig();
		resultJsonConfig.put(Long.class, new ObjectSerializer() {
			@Override
			public void write(JSONSerializer serializer, Object object, Object arg2, Type arg3)
					throws IOException {
				SerializeWriter out = serializer.getWriter();
				out.writeString(Objects.toString(object, null));
			}
		});

		String rtnText = JSON.toJSONString(object, resultJsonConfig,
				SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteEnumUsingToString);
		return rtnText;
	}
	
	public static Map<String, String> parseToMap(String str) {
		return JSONObject.parseObject(str, new TypeReference<Map<String, String>>() {
		});
	}
}
